package com.example.spring.framework.aop.intercept;

import com.example.spring.framework.aop.aspect.JoinPoint;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname MethodInvocation
 * @Date 2019/4/22 23:53
 * @Author admin
 * @Description TODO
 */
public class MethodInvocation implements JoinPoint {

    private Object proxy;
    private Object target;
    private Method method;
    private Object[] atguments;
    private Class<?> targetClass;
    private List<Object> interceptorsAndDynamicMethodMatchers;

    private Map<String, Object> userAttribute;

    private int currentInterceptorIndex = -1;

    public MethodInvocation(Object proxy, Object target, Method method, Object[] atguments, Class<?> targetClass, List<Object> interceptorsAndDynamicMethodMatchers) {
        this.proxy = proxy;
        this.target = target;
        this.method = method;
        this.atguments = atguments;
        this.targetClass = targetClass;
        this.interceptorsAndDynamicMethodMatchers = interceptorsAndDynamicMethodMatchers;
    }

    public Object procccd() throws Throwable {
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
            return this.method.invoke(this.target, this.atguments);
        }
        Object interceptorAndInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
        if (interceptorAndInterceptionAdvice instanceof MethodInterceptor) {
            MethodInterceptor interceptor = (MethodInterceptor) interceptorAndInterceptionAdvice;
            return interceptor.invoke(this);
        } else {
            return procccd();
        }
    }

    @Override
    public Object getThis() {
        return this.target;
    }

    @Override
    public Object[] getArguments() {
        return this.atguments;
    }

    @Override
    public Method getMethod() {
        return this.method;
    }

    @Override
    public void setUserAttribute(String key, Object value) {
        if (null != value) {
            if (null == this.userAttribute) {
                this.userAttribute = new HashMap<String, Object>();
            } else {
                this.userAttribute.put(key, value);
            }
        } else {
            if (null != userAttribute) {
                userAttribute.remove(key);
            }
        }
    }

    @Override
    public Object getUserAttribute(String key) {
        return this.userAttribute != null ? userAttribute.get(key) : null;
    }
}
